package com.innovation.sys.common.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.innovation.sys.common.utils.SessionUtils;

public class SessionInterceptor implements HandlerInterceptor {

	private static Logger logger = LoggerFactory.getLogger(HandlerInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("请求的path为:{}" + request.getRequestURL());
		Session session = SessionUtils.getSession();
		if (session.getAttribute("user") == null) {
			this.writeHtml(request, response);
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	private void writeHtml(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		String path = request.getContextPath() + "/login.jsp";
		String content = "<script language='javascript'>alert('会话过期,请重新登录');" + "window.top.location.href='" + path
				+ "';</script>";
		writer.write(content);
		writer.flush();
		writer.close();
	}

}
